import React, { Component, Fragment } from "react";
import { getAllCommodity, addCommodity, deleteCommodity, updateCommodity, getAllCat } from "@/api/commodity";
import { Table, Form, Modal, Button, message, Input, Popconfirm, Upload, Select } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { adminToken } from "@/utils/variable";
const { Option } = Select;
export default class List extends Component {
    constructor() {
        super();
        this.state = {
            columns: [
                {
                    title: "商品名称",
                    width: 150,
                    fixed: "left",
                    dataIndex: "name",
                },
                {
                    title: "商品图片",
                    width: 120,
                    dataIndex: "covers",
                    render: text => (
                        <Fragment>{text && text.length ? <img width="100" src={`${process.env.REACT_APP_FILE}/${text[0]}`} /> : ""}</Fragment>
                    ),
                },
                {
                    title: "价格",
                    width: 100,
                    dataIndex: "price",
                    render: text => <Fragment>￥{text}</Fragment>,
                },
                {
                    title: "排序号",
                    width: 100,
                    dataIndex: "orderIndex",
                },
                {
                    title: "分类",
                    width: 160,
                    ellipsis: true,
                    dataIndex: "cat",
                    render(text) {
                        return <Fragment>{text ? text.title : ""}</Fragment>;
                    },
                },
                {
                    title: "描述",
                    width: 300,
                    dataIndex: "dsc",
                },
                {
                    title: "操作",
                    width: 180,
                    fixed: "right",
                    dataIndex: "operation",
                    render: (text, { name, _id, covers, price, cat, dsc, orderIndex }) => (
                        <div className="operation-wrap">
                            <Button
                                type="primary"
                                onClick={() => {
                                    this.setState(
                                        {
                                            FormModalVisible: true,
                                            editId: _id,
                                            isAdd: false,
                                            covers,
                                        },
                                        () => this.refs.commodityFormRef.setFieldsValue({ name, covers, price, cat: cat._id, dsc, orderIndex })
                                    );
                                }}
                            >
                                编辑
                            </Button>
                            <Popconfirm
                                title={`确定删除${name}吗？`}
                                okText="确定"
                                cancelText="取消"
                                onConfirm={() => {
                                    deleteCommodity({ _id }).then(res => {
                                        if (res.code === 200) {
                                            this.getAllCom_com();
                                            message.success("删除成功");
                                        } else {
                                            message.warn(res.message);
                                        }
                                    });
                                }}
                            >
                                <Button danger>删除</Button>
                            </Popconfirm>
                        </div>
                    ),
                },
            ],
            dataSource: [],
            FormModalVisible: false,
            pagination: {
                current: 1,
                pageSize: 10,
                total: 0,
                onChange: (current, pageSize) => {
                    this.setState({ pagination: { ...this.state.pagination, current, pageSize } }, () => {
                        this.getAllCom_com();
                    });
                },
            },
            allCat: [],
            covers: [],
            isAdd: true,
        };
    }
    UNSAFE_componentWillMount() {
        this.getAllCom_com();
        this.getAllCat_com();
    }
    getAllCat_com() {
        getAllCat({ pageSize: 999 }).then(res => {
            if (res.code === 200) {
                this.setState({ allCat: res.data });
            }
        });
    }
    getAllCom_com() {
        const { current, pageSize } = this.state.pagination;
        getAllCommodity({ current, pageSize }).then(res => {
            if (res.code === 200) {
                this.setState({
                    dataSource: res.data.map(item => ({ ...item, key: item._id })),
                    pagination: { ...this.state.pagination, total: res.total },
                });
            }
        });
    }
    render() {
        const { columns, dataSource, FormModalVisible, pagination, allCat, covers, isAdd, editId } = this.state;
        return (
            <>
                <div className="mb-10">
                    <Button
                        type="primary"
                        onClick={() => {
                            this.setState({ FormModalVisible: true, isAdd: true, covers: [] }, () => this.refs.commodityFormRef.resetFields());
                        }}
                    >
                        添加商品
                    </Button>
                </div>
                <Table
                    columns={columns}
                    dataSource={dataSource}
                    pagination={pagination}
                    scroll={{
                        x: columns.reduce((pre, item) => {
                            return (pre.width ? pre.width : pre) + (item.width ? item.width : 0);
                        }),
                        y: 600,
                    }}
                />
                <Modal
                    title={`添加/修改商品`}
                    visible={FormModalVisible}
                    cancelText="取消"
                    okText="确认"
                    onCancel={() =>
                        this.setState({
                            FormModalVisible: false,
                        })
                    }
                    keyboard={true}
                    onOk={() => {
                        this.refs.commodityFormRef.validateFields().then(formData => {
                            formData.covers = covers;
                            if (isAdd) {
                                addCommodity(formData).then(res => {
                                    if (res.code == 200) {
                                        this.getAllCom_com();
                                        this.setState({ FormModalVisible: false });
                                        message.success("添加成功");
                                    } else {
                                        message.error(res.message);
                                    }
                                });
                            } else {
                                updateCommodity({ _id: editId, ...formData }).then(res => {
                                    if (res.code == 200) {
                                        this.getAllCom_com();
                                        this.setState({ FormModalVisible: false });
                                        message.success("修改成功");
                                    } else {
                                        message.error(res.message);
                                    }
                                });
                            }
                        });
                    }}
                >
                    <Form ref="commodityFormRef" wrapperCol={{ span: 12 }} labelCol={{ span: 7 }} initialValues={{ orderIndex: 20 }}>
                        <Form.Item name="name" label="商品名称" rules={[{ required: true, message: "商品名称不能为空" }]}>
                            <Input />
                        </Form.Item>
                        <Form.Item name="dsc" label="描述" rules={[{ required: true, message: "描述不能为空" }]}>
                            <Input />
                        </Form.Item>
                        <Form.Item name="cat" label="商品分类" rules={[{ required: true, message: "商品分类不能为空" }]}>
                            <Select>
                                {allCat.map(item => (
                                    <Option key={item._id} value={item._id}>
                                        {item.title}
                                    </Option>
                                ))}
                            </Select>
                        </Form.Item>
                        <Form.Item name="price" label="价格" rules={[{ required: true, message: "价格不能为空" }]}>
                            <Input type="number" min={0} addonAfter={<Fragment>元</Fragment>} />
                        </Form.Item>
                        <Form.Item name="orderIndex" label="排序号" rules={[{ required: true, message: "排序号不能为空" }]}>
                            <Input type="number" maxLength={3} max={100} min={0} />
                        </Form.Item>
                        <Form.Item label="商品图片">
                            <div className="jc-start ai-start upload-wrap">
                                {covers.map((item, index) => (
                                    <Upload
                                        key={index}
                                        fileList={[]}
                                        action={process.env.REACT_APP_FILE}
                                        headers={{ Authorization: `Bearer ${localStorage[adminToken]}` }}
                                        listType="picture-card"
                                        onChange={info => {
                                            if (info.file.status == "done") {
                                                let newCovers = JSON.parse(JSON.stringify(covers));
                                                newCovers[index] = info.file.response.originalname;
                                                this.setState({ covers: newCovers });
                                            }
                                        }}
                                    >
                                        <img width="100%" src={`${process.env.REACT_APP_FILE}/${item}`} />
                                    </Upload>
                                ))}
                                <Form.Item name="covers">
                                    <Upload
                                        fileList={[]}
                                        action={process.env.REACT_APP_FILE}
                                        headers={{ Authorization: `Bearer ${localStorage[adminToken]}` }}
                                        listType="picture-card"
                                        onChange={info => {
                                            if (info.file.status == "done") {
                                                let newCovers = JSON.parse(JSON.stringify(covers));
                                                newCovers.push(info.file.response.originalname);
                                                this.setState({ covers: newCovers }, () => {
                                                    let uploadWrap = document.getElementsByClassName("upload-wrap")[0];
                                                    document.getElementsByClassName("upload-wrap")[0].scrollLeft =
                                                        uploadWrap.scrollWidth - uploadWrap.clientWidth;
                                                });
                                            }
                                        }}
                                    >
                                        <PlusOutlined />
                                    </Upload>
                                </Form.Item>
                            </div>
                        </Form.Item>
                    </Form>
                </Modal>
            </>
        );
    }
}
